package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyThemeQuery;
import cn.wolfcode.luowowo.repository.StrategyThemeRepository;
import cn.wolfcode.luowowo.service.IStrategyThemeService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class StrategyThemeServiceImpl implements IStrategyThemeService {
    

    //Spring-boot集成redis持久化数据库
    @Autowired
    private StrategyThemeRepository repository;
    
    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyTheme strategyTheme) {

        strategyTheme.setId(null);
        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {

        repository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {

        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> listAll() {
        return repository.findAll();
    }


    // 攻略列表更新/添加
    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {

        if(StringUtils.hasLength(strategyTheme.getId())){
           this.update(strategyTheme);
        }else{
            this.save(strategyTheme);
        }
    }

    // 攻略分页查询
    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {

        Query query = new Query();

        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(), Sort.Direction.ASC,"_id");
        
        return DBHelper.query(template,StrategyTheme.class,query,pageable);
    }

}
